package com.authine.cloudpivot.app.openapi.config;

import com.authine.cloudpivot.app.openapi.domain.gateway.DynamicRouteGateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * @author carter
 * create_date  2020/6/4 16:16
 * description     路由配置
 */
@Slf4j
@Configuration
public class RouteConfig implements InitializingBean {

    private final DynamicRouteGateway dynamicRouteGateway;

    @Value(value = "${spring.webflux.base-path}")
    private String applicationBashPath;


    public RouteConfig(DynamicRouteGateway dynamicRouteGateway) {
        this.dynamicRouteGateway = dynamicRouteGateway;
    }


    @ConditionalOnProperty(value = "swagger.open", havingValue = "open")
    @Bean
    public RouterFunction<ServerResponse> staticResourceRouter() {
        return RouterFunctions.resources(applicationBashPath + "/**", new ClassPathResource("public/"));
    }

    @Bean
    public RouteLocator mvpRoutes(RouteLocatorBuilder builder) {
        return builder.routes().build();

    }


    @Override
    public void afterPropertiesSet() throws Exception {
        dynamicRouteGateway.initRoute();
    }
}
